﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;
using static System.Net.Mime.MediaTypeNames;

namespace WTAppletProjectHTTPS.Controllers
{
    [JwtAuthentication]
    public class ColaProductFunctionTestController : ApiController
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] ColaProductFunctionTest CPFT)
        {
            ReturnObject RO = new ReturnObject();
            if (CPFT == null ||
                            string.IsNullOrEmpty(CPFT.CPFT_LineBody) ||
                            string.IsNullOrEmpty(CPFT.CPFT_ProductModel) ||
                            string.IsNullOrEmpty(CPFT.CPFT_OrderModel) ||
                            string.IsNullOrEmpty(CPFT.CPFT_Inspector))
            {
                Logger.Warn("输入值无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "输入值无效";
                RO.Data = CPFT;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var query = @"INSERT INTO ColaProductFunctionTest 
                                    (CPFTDate, CPFTLineBody, CPFTProductModel, CPFTOrderModel, CPFTInspector, 
                                     CPFTInspectionItem, CPFTTerminalTorque, CPFTOverallPulloutForce, CPFTSimulationInstallation, 
                                     CPFTHighVoltageTest, CPFTProbeTest, CPFTContactGaugeNonContactGaugeSocket,CPFTCreateCreator,CPFTCreateTime)
                                    VALUES 
                                    (@Date, @LineBody, @ProductModel, @OrderModel, @Inspector, 
                                     @InspectionItem, @TerminalTorque, @OverallPulloutForce, @SimulationInstallation, 
                                     @HighVoltageTest, @ProbeTest, @ContactGaugeNonContactGaugeSocket,@CreateCreator,@CreateTime);
                                    SELECT CAST(scope_identity() AS int);"
;
                        SqlParameter[] parameters = {
                            new SqlParameter("@Date", SqlDbType.DateTime) { Value = CPFT.CPFT_Date },
                            new SqlParameter("@LineBody", SqlDbType.NVarChar, 50) { Value = CPFT.CPFT_LineBody },
                            new SqlParameter("@ProductModel", SqlDbType.NVarChar, 50) { Value = CPFT.CPFT_ProductModel },
                            new SqlParameter("@OrderModel", SqlDbType.NVarChar, 50) { Value = CPFT.CPFT_OrderModel },
                            new SqlParameter("@Inspector", SqlDbType.NVarChar, 50) { Value = CPFT.CPFT_Inspector },
                            new SqlParameter("@InspectionItem", SqlDbType.NVarChar, 50) { Value = CPFT.CPFT_InspectionItem },
                            new SqlParameter("@TerminalTorque", SqlDbType.NVarChar, 50) { Value = (object)CPFT.CPFT_TerminalTorque ?? DBNull.Value },
                            new SqlParameter("@OverallPulloutForce", SqlDbType.NVarChar, 50) { Value = (object)CPFT.CPFT_OverallPulloutForce ?? DBNull.Value },
                            new SqlParameter("@SimulationInstallation", SqlDbType.NVarChar, 50) { Value = (object)CPFT.CPFT_SimulationInstallation ?? DBNull.Value },
                            new SqlParameter("@HighVoltageTest", SqlDbType.NVarChar, 50) { Value = (object)CPFT.CPFT_HighVoltageTest ?? DBNull.Value },
                            new SqlParameter("@ProbeTest", SqlDbType.NVarChar, 50) { Value = (object)CPFT.CPFT_ProbeTest ?? DBNull.Value },
                            new SqlParameter("@ContactGaugeNonContactGaugeSocket", SqlDbType.NVarChar, 50) { Value = (object)CPFT.CPFT_ContactGaugeNonContactGaugeSocket ?? DBNull.Value },
                             new SqlParameter("@CreateCreator", SqlDbType.NVarChar, 50) { Value = CPFT.CPFT_CreateCreator },
                             new SqlParameter("@CreateTime", SqlDbType.DateTime) { Value = DateTime.Now },
                        };

                        using (var command = new SqlCommand(query, connection, transaction))
                        {
                            command.Parameters.AddRange(parameters);
                            var result = await command.ExecuteScalarAsync();
                            if (result != null)
                            {
                                transaction.Commit();
                                CPFT.CPFT_ID = Convert.ToInt32(result);
                                Logger.Info("新增成功");
                                RO.Status = HttpStatusCode.OK;
                                RO.Message = "OK";
                                RO.Data = CPFT;
                                return Request.CreateResponse(HttpStatusCode.OK, RO);
                            }
                            else
                            {
                                transaction.Rollback();
                                Logger.Error("插入记录失败: ");
                                RO.Status = HttpStatusCode.InternalServerError;
                                RO.Message = "Error";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Logger.Warn("新增失败: " + ex.Message);
                        RO.Status = HttpStatusCode.InternalServerError;
                        RO.Message = "Error" + ex.Message;
                        RO.Data = null;
                        return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                    }
                }
            }
        }
    }
}